/*******************************************************************************
*  file    : file_format_simple.cpp
*  created : 19.06.2014
*  author  : Slyshyk Oleksiy (alexSlyshyk@gmail.com)
*******************************************************************************/

#include "file_format_simple.hpp"
#include <QStringList>
#include <QTextStream>
#include <QFile>
#include <QDebug>


QString FileFormatSimple::name() const
{
    return QStringLiteral("simple");
}

QStringList FileFormatSimple::formats() const
{
    QStringList res;
    res << QStringLiteral("simple") << QStringLiteral("dat");
    return res;
}

QString FileFormatSimple::fileFilter() const
{
    return QStringLiteral("Data (*.dat)");
}

void FileFormatSimple::setName(const QString &f)
{
    fileName_ = f;
}

double FileFormatSimple::sampleRate() const
{
    if(data_.size())
        return static_cast<double>(data_.size()) / dataTime_;
    else
        return 0.0;
}

QVector<std::complex<double> > FileFormatSimple::getData()
{
    return data_;
}

bool FileFormatSimple::read()
{
    QFile file(fileName_);
    if(!file.open(QIODevice::Text | QIODevice::ReadOnly))
        {
            qWarning() << "Can't open "<< fileName_;
            return false;
        }

    int cnt = -1;
    QTextStream out(&file);

    out >> cnt >> dataTime_;
    //qDebug() << cnt << " " << dataTime_ ;

    data_.reserve(cnt);
    try
    {
        double d;
        while( !out.atEnd())
            {
                out >> d;
                data_.push_back(d);
            }
        if(data_.size() > cnt)
            data_.resize(cnt);
    }
    catch(std::exception & e)
    {
        qDebug() << e.what();
        data_.resize(0);
    }

    if(cnt != data_.size())
        qDebug() << QString("Read CNT = %1, but real samples cnt = %2 .").arg(cnt).arg(data_.size());
    //qDebug() << "Read " << data_.size() << " samples.";

    file.close();

    return true;
}

bool FileFormatSimple::read(const QString &f)
{
    fileName_ = f;
    return read();
}

void FileFormatSimple::flush()
{
    data_.resize(0);
    dataTime_ = 0.0;
    fileName_ = "no file";
}
